from django.conf import settings
from celery import shared_task
from mysqldb.weChatSDK import *

import logging

logger = logging.getLogger("wechat")


@shared_task
def WeChat_Template_List(tid, data):
    """模板列表"""
    if tid == "服务进度提醒":
        d = {
            "thing1": {"value": data[0]},  # 服务名称
            "thing2": {"value": data[1]},  # 服务项目
            "thing3": {"value": data[2]},  # 服务人员
            "thing4": {"value": data[3]},  # 服务阶段
            "time5": {"value": data[4]},  # 服务时间
        }
        return ["opFd6AJghk13em67olWQwO8RFVmd-lFR7s761KXBQhY", d]
    if tid == "服务进度提醒":
        d = {
            "character_string4": {"value": data[0]},  # 订单号
            "thing8": {"value": data[1]},  # 服务人员
            "time9": {"value": data[2]},  # 评价时间
            "phrase12": {"value": data[3]},  # 服务状态
            "thing5": {"value": data[4]},  # 备注
        }
        return ["I62phj9rwr4jsbNtyVZFJwkSwEKTpIlFjYkjsrcJLUM", d]
    return None


@shared_task
def WeChat_Template_Message(obj):
    """微信小程序订阅消息"""
    # print(obj)
    # if settings.DEBUG:
    #     return
    # 实例化小程序接口
    WX = requests_SDK()
    WX.getConf()
    for i in obj.get("unids"):
        if not i:
            continue
        m = obj.get("template")
        if not m:
            continue
        d = WeChat_Template_List(m, obj.get("datas"))
        if not d:
            continue

        url = "/cgi-bin/message/subscribe/send"
        headers = WX.has_headers()
        headers["Content-Type"] = "application/json"
        params = {"access_token": WX.has_access_token()}
        data = {
            "template_id": d[0],
            "page": "LoginBefor/callOrder/callOrder",
            "touser": i,
            "data": d[1],
            "miniprogram_state": settings.STATE,
            "lang": "zh_CN",
        }
        r = WX.do_post(url, headers=headers, params=params, data=json.dumps(data))
        if not r or r.get("errcode"):
            logger.warning(f'发送订阅消息错误 {i} {r.get("errmsg")}')
